<?php
/**
 * Created by PhpStorm.
 * User: kan.yang@starcor.cn
 * Date: 18-3-9
 * Time: 下午4:23
 */
set_time_limit(0);ini_set('display_errors',1);
//header('Content-Type:text/xml; charset=utf-8');
include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/common.php";
\ns_core\m_load::load("ns_core.m_config");
class import_cdn_media
{
    //数据库/缓存处理类
    private $obj_dc = null;
    //SP ID
    private $str_sp_id = 'bflt_xiaole';
    //允许上传的文件格式
    private $arr_file_extension = array('csv');

    /**
     * 默认构造函数
     */
    public function __construct()
    {
        //数据库操作类
        $this->obj_dc = m_config::get_dc();
        //SP ID
        $this->str_sp_id = isset($_REQUEST['sp_id']) && $_REQUEST['sp_id'] > 0 ? $_REQUEST['sp_id'] : $this->str_sp_id;
        //导出文件保存路径
        $this->str_csv_path  = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/data/media_cdn_flow/import/' . $this->str_sp_id . '/';
    }

    /**
     * 导入文件
     * @return bool
     */
    public function import_csv_file()
    {
        $arr_file = $_FILES['csv'];

        //验证上传文件是否异常
        if(!empty($arr_file['error']) || $arr_file['size'] <= 0)
        {
            $this->_callback_info(1,'上传文件失败');
        }
        $arr_path_info = pathinfo($arr_file['name']);
        //验证文件格式
        if(!in_array($arr_path_info['extension'],$this->arr_file_extension))
        {
            $this->_callback_info(1,'文件格式不正确，允许扩展名：' . var_export($this->arr_file_extension,true));
        }
        //生成新的存储路径
        if(!is_dir($this->str_csv_path))
        {
            $bool_dir_ret = mkdir($this->str_csv_path,0777,true);
            if(!$bool_dir_ret)
            {
                return $this->_callback_info(1,'导入片源数据的保存路径创建失败。路径：' . $this->str_csv_path);
            }
        }
        //生成文件
        $obj_guid = new np_guid_class();
        $str_file_path = $this->str_csv_path . $obj_guid->get_guid() . '.' . $arr_path_info['extension'];
        $obj_file = fopen($str_file_path,'w');
        if(file_exists($str_file_path))
        {
            chmod($str_file_path,0777);
            fclose($obj_file);
        }
        else
        {
            return $this->_callback_info(1,'导入片源数据的保存路径创建失败。路径：' . $str_file_path);
        }
        //拷贝文件至新的路径
        if(!move_uploaded_file($arr_file['tmp_name'],$str_file_path))
        {
            return $this->_callback_info(1,'保存文件失败');
        }

        return $this->_callback_info(0,'保存文件成功');
    }

    /**
     * 扫描CDN对应的片源信息
     */
    public function execute_media_cdn_flow()
    {
        //遍历文件
        $arr_file_info = array();
        $this->_get_csv_file_all($this->str_csv_path,$arr_file_info);
        if(empty($arr_file_info))
        {
            return $this->_callback_info(1,'未导入任何CSV文件');
        }
        //引入文件
        include_once dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/mgtv_v2/mgtv_init.php';
        include_once dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/mgtv_v2/models/c2_task_model.php';
        //遍历CSV文件
        foreach($arr_file_info as $str_file)
        {
            $obj_handle = fopen($str_file, 'r');
            //解析csv文件
            while(!feof($obj_handle))
            {
                //fgets方法按行读
                $obj_file_content = fgets($obj_handle);
                //判断读到的每一行是否有值
                if (!empty($obj_file_content))
                {
                    $obj_file_content = trim($obj_file_content,'"');
                    $obj_file_content = str_replace('","',',',$obj_file_content);
                    $arr_file_content = explode(",", $obj_file_content);
                    //参数是否有效
                    if(empty($arr_file_content[0]))
                    {
                        continue;
                    }
                    //第一行跳过
                    if(strtoupper($arr_file_content[0]) == 'NAME' || strtoupper($arr_file_content[1]) == 'CODE' || strtoupper($arr_file_content[2]) == 'ACCESS_URL' || strtoupper($arr_file_content[3]) == 'CSPID')
                    {
                        continue;
                    }
                    //更新C2队列任务结果
                    c2_task_model::save_c2_notify(array(
                        'nns_id' => $arr_file_content[0],
                        'nns_notify_result' => (empty($arr_file_content[2]) ? -1 : 0),
                        'nns_notify_result_url' => '',
                    ));
                    //更新片源播放串
                    if(!empty($arr_file_content[2]))
                    {
                        $str_play_url = json_encode(array(
                            'play_url' => $arr_file_content[2]
                        ));
                        $str_modify_sql = "UPDATE nns_vod_media SET nns_ext_url = '" . addslashes($str_play_url) . "',nns_media_service = 'playurl' WHERE
                                            nns_id IN
                                              (SELECT
                                                `nns_ref_id`
                                              FROM
                                                `nns_mgtvbk_c2_task`
                                              WHERE nns_id IN
                                                (SELECT
                                                  nns_task_id
                                                FROM
                                                  `nns_mgtvbk_c2_log`
                                              WHERE nns_id = '" . $arr_file_content[0] . "'))";
                        nl_execute_by_db($str_modify_sql,$this->obj_dc->db());
                    }
                }
                unset($obj_file_content); usleep(20000);
            }
            //关闭文件流
            fclose($obj_handle); unlink($str_file); usleep(50000);
        }

        return $this->_callback_info(0,'关联完成');
    }

    /**
     * 遍历所有文件目录所有CSV文件
     */
    private function _get_csv_file_all($str_file_path,&$arr_file_info)
    {
        if(is_dir($str_file_path))
        {
            if ($obj_dh = opendir($str_file_path))
            {
                $str_file_base_path = '';
                while(($str_file = readdir($obj_dh)) !== false)
                {
                    if($str_file == "." || $str_file == "..")
                    {
                        continue;
                    }
                    else
                    {
                        $str_file_base_path = $str_file_path . $str_file;
                        if((is_dir($str_file_base_path . '/')))
                        {
                            $this->_get_csv_file_all($str_file_base_path . "/",$arr_file_info);
                        }
                        else
                        {
                            if(filesize($str_file_base_path) > 0)
                            {
                                array_push( $arr_file_info,$str_file_base_path);
                            }
                        }
                    }
                    $str_file_base_path = '';
                }
                closedir($obj_dh);
            }
        }
    }

    /**
     * 输出结果
     * @param int $int_ret
     * @param string $str_reason
     * @return bool
     */
    private function _callback_info($int_ret = 0,$str_reason = '')
    {
        return array('ret' => $int_ret, 'reason' => $str_reason);
    }
}

if(!isset($_REQUEST['action']))
{
    $obj_import_cdn_media = new import_cdn_media();
    $obj_import_cdn_media->execute_media_cdn_flow();
}